//
//  HEPersonCenterViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/11.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEPersonCenterViewController.h"
#import "LEEAlert.h"
#import "HXPhotoPicker.h"
#import "HEReportTextViewCell.h"
#import "HEReportTitleInputCell.h"
#import "HEReportSelectCell.h"
#import "HEOrderTitleCell.h"
#import "HEReportTextCell.h"
#import "HEAddPhotoCell.h"
#import "HEPersonHeadCell.h"
#import "HEOtherBindPhoneViewController.h"

@interface HEPersonCenterViewController ()<UITableViewDelegate, UITableViewDataSource, QMUITextFieldDelegate, HX_PhotoEditViewControllerDelegate>

@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) GDFormModel *formModel;
@property (nonatomic, strong) NSMutableArray *sections;
@property (nonatomic, strong) UIButton *bottomView;

// 创建一个全局的group
@property (nonatomic, strong) dispatch_group_t group;
@property (nonatomic, assign) CGFloat topHeight;

@property (nonatomic, strong) QMUITextField *searchTF;

@property(nonatomic,strong) HXPhotoManager *photoManage;
@property (strong, nonatomic) HXPhotoEdit *photoEdit;

@end

@implementation HEPersonCenterViewController

- (GDFormModel *)formModel {
    if (!_formModel) {
        _formModel = [[GDFormModel alloc] init];
        _formModel.proxyVC = self;
    }
    return _formModel;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"个人信息";
     
    [self initUI];
    [self initCell];
    [self initTabBarView];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshUserInfo) name:KNotificationUserInfoChange object:nil];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:KNotificationUserInfoChange object:nil];
}

- (void)refreshUserInfo {
    _formModel.pi_phone = [UserManager sharedUserManager].curUserInfo.username;
    [self.tableView reloadData];
}

- (void)showAlert {
    UIView *warp = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 200, 115)];
//    warp.backgroundColor = [UIColor colorWithRed:43/255.0f green:133/255.0f blue:208/255.0f alpha:1.0f];
    
    // 输入框
    QMUITextField *searchTF = [[QMUITextField alloc] init];
    searchTF.backgroundColor = KHexColor(@"F1F3F8");
    searchTF.layer.cornerRadius = 8;
    searchTF.font = DYFont(16);
    searchTF.placeholder = @"请输入昵称（8个字符内）";
    searchTF.textInsets = UIEdgeInsetsMake(0, 10, 0, 0);
    searchTF.placeholderColor = [UIColor colorWithHexString:@"#AAAAAA"];
    searchTF.text = self.formModel.pi_nicename;
//    searchTF.delegate = self;
    _searchTF = searchTF;
    [warp addSubview:searchTF];

    [searchTF mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(warp).mas_offset(0);
        make.left.equalTo(warp).offset(10);
        make.right.equalTo(warp).offset(-10);
        make.height.mas_offset(45);
    }];


    // 底部按钮
    UIView *btnWarp = [UIView new];
    [warp addSubview:btnWarp];

    [btnWarp mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(searchTF.mas_bottom).mas_offset(30);
        make.right.equalTo(warp);
        make.left.equalTo(warp);
        make.height.mas_offset(36);
    }];

    QMUIGhostButton *refuseBtn = [[QMUIGhostButton alloc] initWithGhostColor:CNavBgColor];
    refuseBtn.titleLabel.font = UIFontMake(16);
    [refuseBtn setTitle:@"取消" forState:UIControlStateNormal];
    [btnWarp addSubview:refuseBtn];

    QMUIFillButton *agreeBtn = [[QMUIFillButton alloc] initWithFillColor:CNavBgColor titleTextColor:CNavBgFontColor];
    agreeBtn.titleLabel.font = UIFontMake(16);
    [agreeBtn setTitle:@"确定" forState:UIControlStateNormal];
    [btnWarp addSubview:agreeBtn];

    [refuseBtn addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
    [agreeBtn addTarget:self action:@selector(agreenClick) forControlEvents:UIControlEventTouchUpInside];

    [refuseBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(btnWarp);
        make.left.equalTo(btnWarp);
        make.width.mas_offset(100);
        make.height.mas_offset(36);
    }];

    [agreeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(btnWarp);
        make.right.equalTo(btnWarp);
        make.width.mas_offset(100);
        make.height.mas_offset(36);
    }];


    [LEEAlert alert].config
    .LeeTitle(@"请输入昵称")
    .LeeAddCustomView(^(LEECustomView *custom) {

        custom.view = warp;

        custom.isAutoWidth = YES;

//                custom.positionType = LEECustomViewPositionTypeRight;
    })
    .LeeItemInsets(UIEdgeInsetsMake(10, 10, 10, 10)) // 想为哪一项设置间距范围 直接在其后面设置即可 ()
    .LeeItemInsets(UIEdgeInsetsMake(10, -10, 0, -10))
    .LeeShow();
    
    [_searchTF becomeFirstResponder];
}

- (void)cancelClick {
    [LEEAlert closeWithCompletionBlock:^{
        [self.searchTF resignFirstResponder];
    }];
}

- (void)agreenClick {
    if ([DYTools isBlankString:_searchTF.text]) {
        [Dialog toastBottom: @"请输入昵称"];
        return;
    }
    
    if (_searchTF.text.length > 8) {
        [Dialog toastBottom: @"昵称限制在8个字符内！"];
        return;
    }
    
    _formModel.pi_nicename = _searchTF.text;
    [LEEAlert closeWithCompletionBlock:^{
        
        if (![self.formModel.pi_nicename isEqualToString:[UserManager sharedUserManager].curUserInfo.nickname]) {
            [self updateUserInfo];
        }
        [self.searchTF resignFirstResponder];
    }];
}

- (void)initUI {
   _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight, KScreenWidth, KScreenHeight- ZXNavBarHeight - ZXSafeAreaBottom) style:UITableViewStyleGrouped];
    _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, CGFLOAT_MIN)];
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.showsHorizontalScrollIndicator = NO;
    
   _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
   _tableView.scrollsToTop = YES;
   _tableView.tableFooterView = [[UIView alloc] init];
   
   self.tableView.backgroundColor = KWhiteColor;
   self.tableView.delegate = self;
   self.tableView.dataSource = self;
   [self.view addSubview:self.tableView];
}

- (void)initCell {
    // 总段
    _sections = [NSMutableArray array];
    NSMutableArray *classArr = [NSMutableArray array];
    
    UserInfo *user =  [UserManager sharedUserManager].curUserInfo;

    self.formModel.pi_userIco = user.avatar;
    self.formModel.pi_nicename = user.nickname;
    self.formModel.pi_phone = user.username;
    self.formModel.pi_realName = user.realname;
    self.formModel.pi_sex = [HEEnums sexToText:user.sex];
    self.formModel.pi_healthCode = user.healthCode;
     
    GDFiterCellModel *userIconModel = [GDFiterCellModel new];
    userIconModel.cellKlass = HEPersonHeadCell.class;
    userIconModel.leftTitle = @"头像";

    GDFiterCellModel *niceNameModel = [GDFiterCellModel new];
    niceNameModel.cellKlass = HEReportTitleInputCell.class;
    niceNameModel.leftTitle = @"昵称";
    niceNameModel.placeHolder = @"";
    niceNameModel.enable = NO;
    niceNameModel.showArrow = YES;
    niceNameModel.contentColor = CNavDargGrayColor;
    niceNameModel.tableKey = @"pi_nicename";
 
    GDFiterCellModel *phoneModel = [GDFiterCellModel new];
    phoneModel.cellKlass = HEReportTitleInputCell.class;
    phoneModel.leftTitle = @"手机号";
    phoneModel.placeHolder = @"";
    phoneModel.enable = NO;
    phoneModel.showArrow = YES;
    phoneModel.contentColor = CNavDargGrayColor;
    phoneModel.tableKey = @"pi_phone";
    
    GDFiterCellModel *realNameModel = [GDFiterCellModel new];
    realNameModel.cellKlass = HEReportTitleInputCell.class;
    realNameModel.leftTitle = @"姓名";
    realNameModel.placeHolder = @"";
    realNameModel.enable = NO;
    realNameModel.tableKey = @"pi_realName";

    GDFiterCellModel *sexModel = [GDFiterCellModel new];
    sexModel.cellKlass = HEReportTitleInputCell.class;
    sexModel.leftTitle = @"性别";
    sexModel.placeHolder = @"";
    sexModel.enable = NO;
    sexModel.tableKey = @"pi_sex";
    
    GDFiterCellModel *healthModel = [GDFiterCellModel new];
    healthModel.cellKlass = HEReportTitleInputCell.class;
    healthModel.leftTitle = @"健康码";
    healthModel.placeHolder = @"";
    healthModel.enable = NO;
    healthModel.tableKey = @"pi_healthCode";
     
    
    NSMutableArray *secs1 = @[userIconModel, niceNameModel, phoneModel, realNameModel, sexModel, healthModel].mutableCopy;
    [_sections addObject: secs1];

   // 添加的时候注意顺序，暂未对顺序做处理
   [self.tableView mc_registerCellByFiterModels: secs1];
 
   [_tableView reloadData];
}

- (void)initTabBarView {
    UIButton *bottomView = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomView = bottomView;
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = CNavBgColor;
    _bottomView.titleLabel.font = DYBlodFont(18);
    [bottomView setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [bottomView addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    
    
}

- (void)saveUserPhoto:(UIImage *)image {
    
    if (image == nil) {
        [Dialog toastBottom:@"请选择头像"];
        return;
    }
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_async(queue, ^{
        self.group = dispatch_group_create();
        
        // 上传图片
        [self uploadImage: image];
        
        //因上面请求中有加入dispatch_group_enter 和 dispatch_group_leave,所以真正等待上面线程执行完才执行这里面的请求
        dispatch_group_notify(self.group, queue, ^{
            [self updateUserInfo];
        });
    });
}
 
- (void)updateUserInfo {
    
    if ([DYTools isBlankString: self.formModel.pi_nicename]) {
        [Dialog toastBottom:@"请输入昵称"];
        return;
    }
    
    NSMutableDictionary *dict = @{}.mutableCopy;
    [dict setValue:_formModel.pi_nicename forKey:@"nickname"];
    [dict setValue:_formModel.pi_userIco forKey:@"avatar"];

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KupdateUser parameters:dict success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues: responseObject];
        if (response.success) {
            [Dialog toastBottom: @"修改成功"];
            [UserManager sharedUserManager].curUserInfo.nickname = self.formModel.pi_nicename;
            [UserManager sharedUserManager].curUserInfo.avatar = self.formModel.pi_userIco;
            // 存储用户数据
            [[UserManager sharedUserManager] saveUserInfo: [UserManager sharedUserManager].curUserInfo];
            
            [self.tableView reloadData];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:KNotificationUserInfoChange object:nil];
        }
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)uploadImage:(UIImage *)image {
    dispatch_group_enter(_group);
    NSArray *imgs = @[image];
    
    [WOAFNetWorkingHandle uploadImagesWithBaseURL:KServerUrl suffixUrl:Kbatch parameters:@{} name:nil images: imgs fileNames:nil imageScale:0.8 imageType:nil progress:^(int64_t bytesProgress, int64_t totalBytesProgress) {
    } success:^(id  _Nonnull responseObject) {
        
        HEUploadResponse *response = [HEUploadResponse mj_objectWithKeyValues:responseObject];
        self.formModel.pi_userIco = [response.data.src removeLastStringWith:@","];
        dispatch_group_leave(self.group);

    } failure:^(NSError * _Nonnull error) {
        dispatch_group_leave(self.group);
    }];
}

  

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return _sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   NSMutableArray *sec = _sections[section];
   return sec.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   NSMutableArray *sec = _sections[indexPath.section];
   GDFiterCellModel *fiterModel = sec[indexPath.row];
   
   UITableViewCell *cell = [_tableView mc_dequeueReusableCellWithClassType:fiterModel.cellKlass];
   cell.selectionStyle = UITableViewCellSelectionStyleNone;
   fiterModel.fiterCellModelBlock((MCTableBaseCell *)cell, fiterModel, self.formModel, indexPath);
   return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
  NSMutableArray *sec = _sections[indexPath.section];
   GDFiterCellModel *fiterModel = sec[indexPath.row];

    if (fiterModel.cellType == GDFiterCellTypeSelect_ADDPHOTO ||
        fiterModel.cellType == GDFiterCellTypeSelect_TEXTView) {
        return fiterModel.cellHeight;
    }
   return [tableView fd_heightForCellWithIdentifier: NSStringFromClass(fiterModel.cellKlass) cacheByIndexPath:indexPath configuration:^(MCTableBaseCell *cell) {
              [cell refreshContent:fiterModel formModel:self.formModel indexPath:indexPath];
   }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   NSMutableArray *sec = _sections[indexPath.section];
 
    if (indexPath.row == 0) {
        [self selectPhoto];
    }
    else if (indexPath.row == 1) {
        [self showAlert];
    }else if (indexPath.row == 2) {
        HEOtherBindPhoneViewController *vc = [HEOtherBindPhoneViewController new];
        vc.intoType = HEOtherBindPhoneTypeChangePhone;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)selectPhoto {
    
    HXPhotoBottomViewModel *model1 = [[HXPhotoBottomViewModel alloc] init];
    model1.title = [NSBundle hx_localizedStringForKey:@"拍摄"];
    model1.cellHeight = 65.f;
    
    HXPhotoBottomViewModel *model2 = [[HXPhotoBottomViewModel alloc] init];
    model2.title = [NSBundle hx_localizedStringForKey:@"从手机相册选择"];
    HXWeakSelf
    [HXPhotoBottomSelectView showSelectViewWithModels:@[model1, model2] headerView:nil cancelTitle:nil selectCompletion:^(NSInteger index, HXPhotoBottomViewModel * _Nonnull model) {
        [weakSelf actionClickedButtonAtIndex:index];
    } cancelClick:nil];
}

- (void)actionClickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        if(![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            [self.view hx_showImageHUDText:[NSBundle hx_localizedStringForKey:@"无法使用相机!"]];
            return;
        }
        HXWeakSelf
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (granted) {
                    HXCustomCameraViewController *vc = [[HXCustomCameraViewController alloc] init];
                    vc.doneBlock = ^(HXPhotoModel *model, HXCustomCameraViewController *viewController) {
                        [weakSelf saveUserPhoto: [viewController jumpImage]];
                    };
                    vc.cancelBlock = ^(HXCustomCameraViewController *viewController) {
                        
                    };
                    vc.manager = self.photoManage;
                    vc.isOutside = YES;
                    HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithRootViewController:vc];
                    nav.isCamera = YES;
                    nav.supportRotation = self.photoManage.configuration.supportRotation;
                    nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
                    nav.modalPresentationCapturesStatusBarAppearance = YES;
                    [weakSelf presentViewController:nav animated:YES completion:nil];
                }else {
                    [HXPhotoTools showUnusableCameraAlert:weakSelf];
                }
            });
        }];
    }
     
    else if (buttonIndex == 1) {
        self.photoManage.configuration.saveSystemAblum = YES;
        HXWeakSelf
        HXCustomNavigationController *nav = [[HXCustomNavigationController alloc] initWithManager:self.photoManage doneBlock:^(NSArray<HXPhotoModel *> * _Nullable allList, NSArray<HXPhotoModel *> * _Nullable photoList, NSArray<HXPhotoModel *> * _Nullable videoList, BOOL original, UIViewController * _Nullable viewController, HXPhotoManager * _Nullable manager) {
            HXPhotoModel *model = allList.firstObject;
            [weakSelf.view hx_showLoadingHUDText:@"获取图片中"];
            [model requestPreviewImageWithSize:PHImageManagerMaximumSize startRequestICloud:nil progressHandler:nil success:^(UIImage *image, HXPhotoModel *model, NSDictionary *info) {
                [weakSelf saveUserPhoto: image];
                [weakSelf.view hx_handleLoading];
                weakSelf.photoEdit = nil;
            } failed:^(NSDictionary *info, HXPhotoModel *model) {
                [weakSelf.view hx_handleLoading];
                [weakSelf.view hx_showImageHUDText:@"获取失败"];
            }];
        } cancelBlock:^(UIViewController * _Nullable viewController, HXPhotoManager * _Nullable manager) {
            
        }];
         
        [self presentViewController:nav animated:YES completion:nil];
    }
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return CGFLOAT_MIN;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    NSMutableArray *sec = _sections[section];
    return 10;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *v = [[UIView alloc] init];
    v.backgroundColor = CViewBgColor;
    return v;
}


#pragma mark - TextFiledDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {

    NSString *text = [textField.text stringByReplacingCharactersInRange:range withString:string];
    
    return YES;
}


#pragma mark - lazy

- (HXPhotoManager *)photoManage {
    if (!_photoManage) {
        _photoManage = [[HXPhotoManager alloc] initWithType:HXPhotoManagerSelectedTypePhoto];
        _photoManage.configuration.type = HXConfigurationTypeWXChat;
        _photoManage.configuration.singleSelected = YES;
        _photoManage.configuration.lookGifPhoto = NO;
        _photoManage.configuration.albumListTableView = ^(UITableView *tableView) {
    //            NSSLog(@"%@",tableView);
        };
        _photoManage.configuration.videoMaximumSelectDuration = 15.f;
        _photoManage.configuration.selectVideoBeyondTheLimitTimeAutoEdit = YES;
        _photoManage.configuration.singleJumpEdit = YES;
    //        _manager.configuration.movableCropBox = YES;
        _photoManage.configuration.photoEditConfigur.onlyCliping = YES;
        _photoManage.configuration.photoEditConfigur.aspectRatio = HXPhotoEditAspectRatioType_1x1;
        _photoManage.configuration.photoEditConfigur.onlyCliping = YES;
    }
    return _photoManage;
}

@end
 
